import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import router from '../router'
import request from '../utils/request'
import { ElMessage } from 'element-plus'

export interface UserInfo {
  id: number
  username: string
  avatar: string
  roles: string[]
  permissions: string[]
}

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = reactive<UserInfo>({
    id: 0,
    username: '',
    avatar: '',
    roles: [],
    permissions: []
  })

  // token
  const token = ref<string>(localStorage.getItem('token') || '')

  // 登录状态
  const isLogin = ref<boolean>(!!token.value)

  // 登录
  const login = async (username: string, password: string, captcha: string, captchaKey: string) => {
    try {
      const response = await request({
        url: '/auth/login',
        method: 'post',
        data: {
          username,
          password,
          captcha,
          captchaKey
        }
      })
      
      // 保存token
      token.value = response.data.token
      localStorage.setItem('token', response.data.token)
      isLogin.value = true
      
      // 获取用户信息
      await getUserInfo()
      
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await request({
        url: '/auth/info',
        method: 'get'
      })
      
      // 更新用户信息
      Object.assign(userInfo, response.data)
      
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await request({
        url: '/auth/logout',
        method: 'post'
      })
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除token和用户信息
      resetUserState()
      // 跳转到登录页
      router.push('/login')
    }
  }

  // 重置用户状态
  const resetUserState = () => {
    token.value = ''
    isLogin.value = false
    localStorage.removeItem('token')
    Object.assign(userInfo, {
      id: 0,
      username: '',
      avatar: '',
      roles: [],
      permissions: []
    })
  }

  // 获取验证码
  const getCaptcha = async () => {
    try {
      const response = await request({
        url: '/auth/captcha',
        method: 'get'
      })
      return response.data
    } catch (error) {
      console.error('获取验证码失败:', error)
      throw error
    }
  }

  // 注册用户
  const register = async (userData: any) => {
    try {
      const response = await request({
        url: '/auth/register',
        method: 'post',
        data: userData
      })
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 判断是否有权限
  const hasPermission = (permission: string) => {
    return userInfo.permissions.includes(permission)
  }

  // 判断是否有角色
  const hasRole = (role: string) => {
    return userInfo.roles.includes(role)
  }

  return {
    userInfo,
    token,
    isLogin,
    login,
    getUserInfo,
    logout,
    resetUserState,
    getCaptcha,
    register,
    hasPermission,
    hasRole
  }
})